using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using _404park.Core.Crawler;

namespace _404park.ApplicationServices.Crawler.Parser.Provider
{
	public class CNNParser : BaseFeedParser
	{
		public override string BaseUrl
		{
			get { return "http://rss.cnn.com/rss/cnn_topstories.rss"; }
		}

		internal protected override IList<Feed> ParseFeed(string responseData)
		{
			var feedList = new List<Feed>();
			var xmlDoc = XDocument.Parse(responseData);
			if (xmlDoc.Root != null)
			{
				var ns = xmlDoc.Root.GetDefaultNamespace();
				xmlDoc.Root.Descendants(ns+ "item").ToList().ForEach(element => feedList.Add(CreateFeedItem(element, ns)));
			}
			return feedList;
		}

		private Feed CreateFeedItem(XElement xElement, XNamespace ns)
		{
			var title = xElement.Element( ns+ "title") != null ? xElement.Element(ns+"title").Value : string.Empty;
			var description = FormatDescription(xElement.Element(ns+"description"));
			var clickUrl = xElement.Element(ns+"link") != null ? xElement.Element(ns+"link").Value : string.Empty;

			var feed = new Feed
			{
				Title = title,
				Description = description,
				ClickUrl = clickUrl,
				DisplayUrl = string.Empty
			};
			return feed;
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="desElement"></param>
		/// <returns></returns>
		private string FormatDescription(XElement desElement)
		{
			if (desElement == null)
				return string.Empty;
			var source = desElement.Value;
			var array = new char[source.Length];
			int sublenght = 0;
			bool hasOpenTag = false;

			for (var i = 0; i < source.Length; i++)
			{
				char let = source[i];
				if (let == '<')
				{
					sublenght = i;
					hasOpenTag = true;
					continue;
				}
				if (let == '>' && hasOpenTag)
				{
					return source.Substring(0, sublenght);
				}

			}
			return source;

		}
	}
}

